<template>
  <div class="app">
    <!-- 头部 -->
    <van-nav-bar
      fixed
      title="广告位"
      :left-text="leftFlag?'返回':''"
      :right-text="addButton?'添加':''"
      :left-arrow="leftFlag"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <!-- 中间 路由占位符 -->
    <transition>
      <router-view></router-view>
    </transition>
    <!-- 底部 -->
    <van-tabbar v-model="active" active-color="#1989fa">
      <van-tabbar-item icon="home-o" @click="goTo('/')">
        <span>首页</span>
        <i slot="icon" class="iconfont icon-index-fill"></i>
      </van-tabbar-item>
      <van-tabbar-item icon="search" @click="goTo('/search')">搜索</van-tabbar-item>
      <van-tabbar-item icon="cart-o" @click="goTo('/shoppcart')" :badge="shopCarNum === 0 ? '' : shopCarNum">购物车</van-tabbar-item>
      <van-tabbar-item icon="setting-o" @click="goTo('/person')">
        <span>会员</span>
        <i slot="icon" class="iconfont icon-icon_zhanghao"></i>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      active: 0,
      leftFlag: false,
      addButton: false
    }
  },

  created () {
    this.active = sessionStorage.getItem('activeTab') || 0
    this.leftFlag = this.$route.path !== '/home'
    this.addButton = this.$route.path === '/search'
    if (!window.localStorage.getItem('buynum')) {
      window.localStorage.getItem('buynum', 0)
    } else {
      this.addShopCar()
    }
  },
  watch: {
    // 监听路由变化
    $route(to, from) {
      // 当前路由
      let arr = ['/home', '/search', '/shoppcart', '/person'];
      if (arr.indexOf(to.path) > -1) {
        this.active = arr.indexOf(to.path);
        sessionStorage.setItem("activeTab", this.active);
      }
      this.leftFlag = to.path != "/home";
      this.addButton = to.path == "/search";
    }
  },
  methods: {
    // 点击导航左侧事件
    onClickLeft() {
      this.$router.go(-1);
    },
    // 点击导航右侧事件
    onClickRight() {
      this.$router.push("/addgoods");
    },
    // 点击tabbar跳转路由
    goTo(path) {
      this.$router.push(path);
    },
    ...mapMutations(['changeNum']),
    addShopCar () {
      this.changeNum(0)
    }
  },
  computed: {
    ...mapState(['shopCarNum'])
  }
};
</script>

<style scoped lang='less'>
.v-enter{
  transform: translateX(50px);
  opacity: 0;
}
.v-enter-active{
  transition: .5s all;
}
.v-enter-to{
  transform: translateX(0);
  opacity: 1;
}
</style>
